package com.funtl.spring.cloud.alibaba.unit.config;

import com.funtl.spring.cloud.alibaba.unit.handler.CustomAuthencationFailureHandler;
import com.funtl.spring.cloud.alibaba.unit.handler.CustomAuthencationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author Mr.Starry
 * @Date 2020/1/4 14:05
 * @Version 1.0
 */
//@Component
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Resource
    private DataSource dataSource;

    @Resource
    private UserAuthencation userAuthencation;


    //成功处理
    @Resource
    private CustomAuthencationSuccessHandler customAuthencationSuccessHandler;

    //失败处理
    @Resource
    private CustomAuthencationFailureHandler customAuthencationFailureHandler;

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //    super.configure(http);
        http.formLogin()
                .loginPage("/login.html")
                //用户在登录页面处理登录的时候 url
                .loginProcessingUrl("/login")
                .successHandler(customAuthencationSuccessHandler)
                .failureHandler(customAuthencationFailureHandler)
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .userDetailsService(userAuthencation)
                .tokenValiditySeconds(3600)
                .and()
                //认证处理
                .authorizeRequests()
                .antMatchers("/login.html","/image/code").permitAll()
                .anyRequest()  //所有的请求
                .authenticated()  //认证之后就可以访问
                .and()
                .csrf().disable();
    }
}
